package com.quad.innovators.salesease.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.quad.innovators.salesease.common.result.PageResultBean;
import com.quad.innovators.salesease.common.utils.SecurityUtils;
import com.quad.innovators.salesease.common.utils.SystemCodeUtils;
import com.quad.innovators.salesease.constants.SystemConstants;
import com.quad.innovators.salesease.converter.SysRoleConverter;
import com.quad.innovators.salesease.enums.IBaseEnum;
import com.quad.innovators.salesease.enums.ResultCode;
import com.quad.innovators.salesease.enums.StatusEnum;
import com.quad.innovators.salesease.enums.SystemCodeEnum;
import com.quad.innovators.salesease.exception.BusinessException;
import com.quad.innovators.salesease.mapper.SysRoleMapper;
import com.quad.innovators.salesease.model.bo.DataPermissionBO;
import com.quad.innovators.salesease.model.common.Option;
import com.quad.innovators.salesease.model.entity.SysRole;
import com.quad.innovators.salesease.model.entity.SysRoleMenu;
import com.quad.innovators.salesease.model.form.SysRoleForm;
import com.quad.innovators.salesease.model.query.SysRolePageQuery;
import com.quad.innovators.salesease.model.vo.SysRolePageVO;
import com.quad.innovators.salesease.service.SysRoleDataPermissionService;
import com.quad.innovators.salesease.service.SysRoleMenuService;
import com.quad.innovators.salesease.service.SysRoleService;
import com.quad.innovators.salesease.service.SysUserRoleService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
 * 角色业务实现类
 *
 * @author haoxr
 * @since 2022/6/3
 */
@Service
@RequiredArgsConstructor
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    private final SysRoleMenuService roleMenuService;
    private final SysUserRoleService userRoleService;
    private final SysRoleConverter roleConverter;
    private final SysRoleDataPermissionService sysRoleDataPermissionService;

    @Override
    public PageResultBean<SysRolePageVO> getRolePage(SysRolePageQuery queryParams) {
        // 查询参数
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        String keywords = queryParams.getKeywords();

        // 查询数据
        Page<SysRole> rolePage = this.page(new Page<>(pageNum, pageSize),
                new LambdaQueryWrapper<SysRole>()
                        .and(StrUtil.isNotBlank(keywords),
                                wrapper ->
                                        wrapper.like(StrUtil.isNotBlank(keywords), SysRole::getName, keywords)
                                                .or()
                                                .like(StrUtil.isNotBlank(keywords), SysRole::getCode, keywords)
                        )
                        .ne(!SecurityUtils.isRoot(), SysRole::getCode, SystemConstants.ROOT_ROLE_CODE) // 非超级管理员不显示超级管理员角色
        );

        // 实体转换
        return roleConverter.toPageVo(rolePage);
    }

    @Override
    public List<Option<String>> listRoleOptions() {
        // 查询数据
        List<SysRole> roleList = this.list(new LambdaQueryWrapper<SysRole>()
                .ne(!SecurityUtils.isRoot(), SysRole::getCode, SystemConstants.ROOT_ROLE_CODE)
                .select(SysRole::getCode, SysRole::getName)
                .orderByDesc(SysRole::getUpdateTime)
        );
        // 实体转换
        return roleConverter.entities2Options(roleList);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveRole(SysRoleForm roleForm) {
        String name = roleForm.getName();
        String roleCode = SystemCodeUtils.getCode(SystemCodeEnum.ROLE);
        long count = this.count(new LambdaQueryWrapper<SysRole>()
                .eq(StringUtils.isNotBlank(name), SysRole::getName, name));
        Assert.isTrue(count == 0, "角色名称已存在，请修改后重试！");
        // 实体转换
        SysRole role = roleConverter.toEntity(roleForm);
        role.setCode(roleCode);
        this.save(role);
        // 新增角色菜单
        assignMenusToRole(roleCode, roleForm.getMenuCodes());
        sysRoleDataPermissionService.add(roleCode, roleForm.getDataPermissionDataList());
        // 刷新角色的权限缓存
        roleMenuService.refreshRolePermsCache(role.getCode());
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateRole(String roleCode, SysRoleForm roleForm) {
        // 编辑角色时，判断角色是否存在

        SysRole oldRole = null;
        if (StringUtils.isNotBlank(roleCode)) {
            oldRole = this.baseMapper.getByCode(roleCode);
            if(oldRole == null) {
                throw BusinessException.resultCode(ResultCode.NOT_FOUND);
            }
        }else {
            throw BusinessException.resultCode(ResultCode.NOT_FOUND);
        }
        long count = this.count(new LambdaQueryWrapper<SysRole>()
                .ne(StringUtils.isNotBlank(roleCode), SysRole::getCode, roleCode)
                .eq(SysRole::getName, roleForm.getName()));
        Assert.isTrue(count == 0, "角色名称已存在，请修改后重试！");
        // 实体转换
        SysRole role = roleConverter.toEntity(roleForm);
        role.setId(oldRole.getId());
        role.setCode(roleCode);
        boolean result = this.saveOrUpdate(role);
        if (result) {
            // 判断角色编码或状态是否修改，修改了则刷新权限缓存
            if (!StrUtil.equals(oldRole.getCode(), roleCode) || !ObjectUtil.equals(oldRole.getStatus(), roleForm.getStatus())) {
                roleMenuService.refreshRolePermsCache(oldRole.getCode(), roleCode);
            }
        }
        assignMenusToRole(roleCode, roleForm.getMenuCodes());
        sysRoleDataPermissionService.add(roleCode, roleForm.getDataPermissionDataList());
        // 刷新角色的权限缓存
        roleMenuService.refreshRolePermsCache(role.getCode());
        return true;
    }


    @Override
    public SysRoleForm getRoleForm(String roleCode) {
        SysRole entity = this.baseMapper.getByCode(roleCode);
        List<DataPermissionBO> dataPermissionBOS = sysRoleDataPermissionService.selectByRole(entity.getCode());
        SysRoleForm form = roleConverter.toForm(entity);
        form.setDataPermissionDataList(dataPermissionBOS);
        return form;
    }


    @Override
    public boolean updateRoleStatus(String roleCode, Integer status) {
        SysRole role = this.baseMapper.getByCode(roleCode);
        Assert.isTrue(role != null, "角色不存在");
        role.setStatus(IBaseEnum.getEnumByValue(status, StatusEnum.class));
        boolean result = this.updateById(role);
        if (result) {
            // 刷新角色的权限缓存
            roleMenuService.refreshRolePermsCache(role.getCode());
        }
        return result;
    }


    @Override
    public boolean deleteRoles(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的角色ID不能为空");
        List<String> roleCodes = Arrays.stream(ids.split(","))
                .toList();

        for (String roleCode : roleCodes) {
            SysRole role = this.baseMapper.getByCode(roleCode);
            Assert.isTrue(role != null, "角色不存在");

            // 判断角色是否被用户关联
            boolean isRoleAssigned = userRoleService.hasAssignedUsers(roleCode);
            assert role != null;
            Assert.isTrue(!isRoleAssigned, "角色【{}】已分配用户，请先解除关联后删除", role.getName());

            boolean deleteResult = this.removeById(role.getId());
            if (deleteResult) {
                // 删除成功，刷新权限缓存
                roleMenuService.refreshRolePermsCache(role.getCode());
            }
        }
        return true;
    }


    @Override
    public List<String> getRoleMenuIds(String roleCode) {
        return roleMenuService.listMenuIdsByRoleId(roleCode);
    }

    @Override
    @Transactional
    @CacheEvict(cacheNames = "menu", key = "'routes'")
    public boolean assignMenusToRole(String roleCode, List<String> menuCodes) {
        SysRole role = this.baseMapper.getByCode(roleCode);
        Assert.isTrue(role != null, "角色不存在");
        // 删除角色菜单
        roleMenuService.remove(
                new LambdaQueryWrapper<SysRoleMenu>()
                        .eq(SysRoleMenu::getRoleCode, roleCode)
        );
        // 新增角色菜单
        if (CollectionUtil.isNotEmpty(menuCodes)) {
            List<SysRoleMenu> roleMenus = menuCodes
                    .stream()
                    .map(menuCode -> new SysRoleMenu(roleCode, menuCode, 1))
                    .toList();
            roleMenuService.saveBatch(roleMenus);
        }
        // 刷新角色的权限缓存
        roleMenuService.refreshRolePermsCache(role.getCode());
        return true;
    }
}
